<template>
  <el-card class="user-card">
    <div class="avatar-container">
      <i class="el-icon-s-custom avatar-icon"></i>
    </div>
    <div class="info-container">
      <div class="header">
        <span class="title">个人信息</span>
        <el-button type="primary" size="small" @click="toggleEdit">
          {{ editMode ? '取消' : '编辑' }}
        </el-button>
      </div>
      <el-form label-width="80px" :model="userData" ref="userForm" class="user-form">
        <el-form-item label="名称">
          <el-input v-model="userData.username" :disabled="!editMode"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userData.password" type="password" show-password :disabled="!editMode"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userData.email" :disabled="!editMode"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="userData.role" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="editMode" class="btn-container">
          <el-button type="primary" @click="saveChanges">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import {mapActions} from "vuex";

export default {
  data() {
    return {
      editMode: false,
      userData: {
        id: '',
        username: '',
        password: '',
        email: '',
        role: '',
      },
    };
  },
  mounted() {
    this.userData.id = this.$store.state.user.userInfo.id;
    this.userData.username = this.$store.state.user.userInfo.username;
    this.userData.email = this.$store.state.user.userInfo.email;
    this.userData.role = this.$store.state.user.userInfo.role;
  },
  methods: {
    ...mapActions(['updateUserInfo']),

    saveChanges() {
        this.updateUserInfo(this.userData).then((success) => {
          if (success) {
            this.$message.success('信息已保存');
            this.editMode = false;
          } else {
            this.$message.error('保存失败，请重试');
          }
        })
    },

    toggleEdit() {
      this.editMode = !this.editMode;
    },
  },
};
</script>

<style scoped>
.user-card {
  max-width: 450px;
  margin: 40px auto;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-icon {
  font-size: 120px;
  color: #888888;
}

.info-container {
  padding: 0 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.user-form .el-form-item {
  margin-bottom: 15px;
}

.btn-container {
  text-align: right;
}
</style>
